<template>
  <div class="workflow-page">
    <!-- 引入字体组件 -->
    <font-loader />
    
    <!-- 页面禁用遮罩：当必需参数缺失时阻止交互并提示 -->
    <div v-if="pageDisabled" class="page-disabled-mask">
      <div class="mask-content">
        <i class="el-icon-warning-outline mask-icon"></i>
        <div class="mask-title">缺少必要参数</div>
        <div class="mask-desc">未获取到 App名称，请通过带有 appName 参数的链接进入本页。</div>
      </div>
    </div>

    <!-- 主要内容区域：左右分栏布局 -->
    <div class="main-layout">
      <!-- 左侧面板：输入控制区 -->
      <div class="left-panel">
        <div class="panel-header">
          <span class="panel-title">三步翻译工作流</span>
          <i class="el-icon-refresh refresh-icon" @click="refreshPage" title="刷新"></i>
        </div>

        <!-- 输入文本区域 -->
        <div class="input-section">
          <div class="section-label">输入文本</div>
          <textarea
            v-model="userInput"
            ref="inputTextarea"
            class="input-textarea"
            placeholder="请输入需要翻译的英文文本..."
            :disabled="isLoading"
            rows="10"
          ></textarea>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button class="btn-clear" @click="clearInput" :disabled="isLoading">
            清除
          </button>
          <button 
            class="btn-execute" 
            @click="handleSend"
            :disabled="isLoading || !userInput.trim()"
          >
            <i class="el-icon-video-play"></i>
            执行
          </button>
        </div>
      </div>

      <!-- 右侧面板：工作流过程和结果展示 -->
      <div class="right-panel">
        <div class="panel-header">
          <span class="panel-title">工作流过程</span>
          <div class="header-actions">
            <i 
              :class="workflowStepsCollapsed ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"
              class="collapse-icon"
              @click="toggleWorkflowSteps"
              title="折叠/展开"
            ></i>
            <i class="el-icon-star-off refresh-icon" title="工作流"></i>
          </div>
        </div>

        <!-- 工作流步骤列表 -->
        <div class="workflow-steps" :class="{ collapsed: workflowStepsCollapsed }">
          <div 
            v-for="(node, index) in workflowSteps" 
            :key="node.nodeId || index"
            class="step-item"
            :class="{
              completed: node.status === 'succeeded',
              running: node.status === 'running',
              failed: node.status === 'failed'
            }"
          >
            <div class="step-icon">
              <i class="el-icon-loading" v-if="node.status === 'running'"></i>
              <i class="el-icon-success" v-else-if="node.status === 'succeeded'"></i>
              <i class="el-icon-error" v-else-if="node.status === 'failed'"></i>
              <i class="el-icon-circle-check" v-else></i>
            </div>
            <div class="step-content">
              <div class="step-title">{{ node.title || node.nodeId || '开始' }}</div>
              <div class="step-status" v-if="node.status === 'running'">运行中</div>
            </div>
          </div>
        </div>

        <!-- 结果展示区域 -->
        <div class="result-section">
          <!-- 机器人背景图片（作为结果区域的背景） -->
          <div class="robot-background-layer">
            <img src="/img/workflow.png" alt="Workflow Robot" class="robot-background" />
          </div>
          
          <div class="result-header">
            <span class="result-title">结果</span>
          </div>

          <!-- 结果内容 -->
          <div class="result-content-wrapper">
            <!-- 思考过程展示 -->
            <div v-if="thoughtContent" class="thought-section">
              <div class="thought-header" @click="toggleThought">
                <span class="thought-title">
                  <i class="el-icon-view"></i>
                  思考过程({{ thoughtTime }}s)
                </span>
                <i :class="thoughtCollapsed ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"></i>
              </div>
              <div class="thought-content" :class="{ collapsed: thoughtCollapsed }" v-html="formatMessage(thoughtContent)"></div>
            </div>

            <!-- 最终结果展示 -->
            <div v-if="resultContent" class="final-result">
              <div class="result-text" v-html="formatResultMessage(resultContent)"></div>
              <div class="result-actions">
                <button class="action-btn" @click="copyResult" title="复制">
                  <i class="el-icon-document-copy"></i>
                </button>
                <button class="action-btn" @click="clearResult" title="清除">
                  <i class="el-icon-delete"></i>
                </button>
              </div>
            </div>

            <!-- 加载中提示 -->
            <div v-if="isLoading && !resultContent" class="loading-indicator">
              <i class="el-icon-loading"></i>
              <span>处理中...</span>
              <button class="stop-btn" @click="stopWorkflow" v-if="currentTaskId">
                <i class="el-icon-video-pause"></i>
                停止
              </button>
            </div>

            <!-- 空状态 -->
            <div v-if="!isLoading && !resultContent && !thoughtContent" class="empty-state">
              <i class="el-icon-document"></i>
              <p>等待执行工作流...</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { runWorkflow, stopWorkflowTask, getWorkflowParameters } from '@/api/dify/workflow'
import { getCurrentUser } from '@/utils/userService'
import FontLoader from '@/components/UserView/general/font.vue'

// 全局函数：切换思考过程显示/隐藏
window.toggleThinkBlock = function(thinkId) {
  const content = document.getElementById(`content-${thinkId}`)
  const icon = document.getElementById(`icon-${thinkId}`)

  if (content && icon) {
    if (content.classList.contains('collapsed')) {
      // 展开
      content.classList.remove('collapsed')
      icon.classList.remove('el-icon-arrow-down')
      icon.classList.add('el-icon-arrow-up')
    } else {
      // 折叠
      content.classList.add('collapsed')
      icon.classList.remove('el-icon-arrow-up')
      icon.classList.add('el-icon-arrow-down')
    }
  }
}

export default {
  name: 'ThreeStepTranslator',
  components: {
    FontLoader
  },
  data() {
    return {
      userInput: '',
      resultContent: '',
      thoughtContent: '',
      isLoading: false,
      currentTaskId: null,
      workflowRunId: null,
      streamController: null,
      appName: '',
      pageDisabled: false,
      workflowSteps: [],
      workflowInputs: {},
      userId: '',
      thoughtCollapsed: false,
      thoughtTime: 0,
      thoughtStartTime: null,
      isInThinkingMode: false, // 标记当前是否处于思考过程模式
      workflowStepsCollapsed: true // 工作流过程折叠状态，默认折叠
    }
  },
  async mounted() {
    // 获取 appName 的优先级：URL参数 > 路由meta > 路由名称映射
    let appName = this.$route.query.appName
    
    // 如果没有 URL 参数，从路由 meta 中获取
    if (!appName && this.$route.meta && this.$route.meta.appName) {
      appName = this.$route.meta.appName
    }
    
    // 如果还没有，根据路由名称映射
    if (!appName) {
      const routeName = this.$route.name
      const routeAppNameMap = {
        'ThreeStepTranslator': 'three_step_translator',
        'LGB_AgentLegal': 'three_step_translator' // 兼容旧路由名称
      }
      appName = routeAppNameMap[routeName]
    }
    
    if (appName) {
      this.appName = appName
      console.log('📝 Workflow - 使用 App名称:', this.appName)
      await this.initializeUserId()
      this.loadWorkflowParameters()
    } else {
      console.warn('⚠️ Workflow - 未找到 App名称，页面将被禁用')
      this.pageDisabled = true
    }
  },
  methods: {
    /**
     * 初始化用户ID
     */
    async initializeUserId() {
      try {
        const userInfo = await getCurrentUser()
        if (userInfo && userInfo.loginName) {
          this.userId = userInfo.loginName
        } else if (userInfo && userInfo.userSn) {
          this.userId = userInfo.userSn
        } else {
          this.userId = 'user_' + Date.now()
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.userId = 'user_' + Date.now()
      }
    },
    
    /**
     * 加载工作流参数
     */
    async loadWorkflowParameters() {
      try {
        const response = await getWorkflowParameters(this.appName)
        if (response.success && response.data) {
          // 处理用户输入表单配置
          if (response.data.user_input_form) {
            this.workflowInputs = this.parseInputForm(response.data.user_input_form)
          }
        }
      } catch (error) {
        console.error('加载工作流参数失败:', error)
      }
    },
    
    /**
     * 解析输入表单配置
     */
    parseInputForm(userInputForm) {
      const inputs = {}
      userInputForm.forEach(item => {
        if (item['text-input']) {
          const field = item['text-input']
          inputs[field.variable] = {
            type: 'text',
            label: field.label,
            required: field.required,
            default: field.default || ''
          }
        } else if (item.paragraph) {
          const field = item.paragraph
          inputs[field.variable] = {
            type: 'paragraph',
            label: field.label,
            required: field.required,
            default: field.default || ''
          }
        } else if (item.select) {
          const field = item.select
          inputs[field.variable] = {
            type: 'select',
            label: field.label,
            required: field.required,
            default: field.default || '',
            options: field.options || []
          }
        }
      })
      return inputs
    },
    
    /**
     * 处理发送消息
     */
    handleSend() {
      if (!this.userInput.trim() || this.isLoading) {
        return
      }
      
      const inputText = this.userInput.trim()
      this.resultContent = ''
      this.thoughtContent = ''
      this.workflowSteps = []
      this.isLoading = true
      this.currentTaskId = null
      this.workflowRunId = null
      this.thoughtTime = 0
      this.thoughtStartTime = Date.now()
      this.isInThinkingMode = false
      
      // 构建 inputs（根据工作流参数配置）
      const inputs = {}
      
      // 如果有配置的输入表单，使用配置
      if (Object.keys(this.workflowInputs).length > 0) {
        Object.keys(this.workflowInputs).forEach(key => {
          // 默认使用用户输入的文本作为第一个文本输入字段
          if (this.workflowInputs[key].type === 'text' || this.workflowInputs[key].type === 'paragraph') {
            if (!inputs[key]) {
              inputs[key] = inputText
              return
            }
          }
        })
      } else {
        // 如果没有配置，使用默认的 query 字段
        inputs.query = inputText
      }
      
      // 发送 Workflow 请求
      this.streamController = runWorkflow(
        {
          inputs: inputs,
          user: this.userId,
          responseMode: 'streaming',
          appName: this.appName
        },
        // onMessage
        (data) => {
          this.handleWorkflowEvent(data)
        },
        // onEnd
        () => {
          this.isLoading = false
          if (this.thoughtStartTime) {
            this.thoughtTime = ((Date.now() - this.thoughtStartTime) / 1000).toFixed(1)
          }
          console.log('Workflow 执行完成')
        },
        // onError
        (error) => {
          this.isLoading = false
          console.error('Workflow 执行错误:', error)
          this.$message.error(error.message || 'Workflow 执行失败')
        }
      )
    },
    
    /**
     * 处理 Workflow 事件
     */
    handleWorkflowEvent(data) {
      console.log('收到 Workflow 事件:', data)
      
      switch (data.event) {
        case 'workflow_started':
          this.workflowRunId = data.workflow_run_id
          this.currentTaskId = data.task_id
          // 添加开始节点
          this.workflowSteps = [{
            nodeId: 'start',
            title: '开始',
            status: 'succeeded'
          }]
          console.log('工作流开始:', this.workflowRunId)
          break
          
        case 'node_started':
          // 添加或更新节点
          const nodeIndex = this.workflowSteps.findIndex(n => n.nodeId === data.data.node_id)
          if (nodeIndex === -1) {
            this.workflowSteps.push({
              nodeId: data.data.node_id,
              nodeType: data.data.node_type,
              title: data.data.title || data.data.node_id,
              index: data.data.index,
              status: 'running'
            })
          } else {
            this.workflowSteps[nodeIndex].status = 'running'
          }
          break
          
        case 'text_chunk':
          // 累积文本内容
          if (data.text) {
            const text = data.text
            
            // 检查思考过程开始标记
            const thinkStartMarkers = [
              '◎ 思考过程',
              '思考过程(',
              '<think>',
              '<think>',
              '分析过程',
              '理解原文',
              '品牌一致性',
              '处理特定术语'
            ]
            
            // 检查正文开始标记
            const resultStartMarkers = [
              '重译',
              '翻译结果',
              '#####',
              '###',
              '翻译：',
              '结果：',
              '输出：'
            ]
            
            // 检查思考过程结束标记
            const thinkEndMarkers = [
              '</think>',
              '</think>',
              '</think>',
              '重译',
              '#####'
            ]
            
            // 检测是否包含思考过程开始标记
            const hasThinkStart = thinkStartMarkers.some(marker => text.includes(marker))
            
            // 检测是否包含正文开始标记
            const hasResultStart = resultStartMarkers.some(marker => text.includes(marker))
            
            // 检测是否包含思考过程结束标记
            const hasThinkEnd = thinkEndMarkers.some(marker => text.includes(marker))
            
            // 状态机：根据标记切换模式
            if (hasThinkStart) {
              // 检测到思考过程开始
              this.isInThinkingMode = true
              this.thoughtContent += text
            } else if (hasResultStart && this.isInThinkingMode) {
              // 检测到正文开始，且当前在思考模式
              // 找到第一个匹配的正文开始标记
              let splitIndex = -1
              let matchedMarker = ''
              for (const marker of resultStartMarkers) {
                const idx = text.indexOf(marker)
                if (idx !== -1 && (splitIndex === -1 || idx < splitIndex)) {
                  splitIndex = idx
                  matchedMarker = marker
                }
              }
              
              if (splitIndex !== -1) {
                // 分离思考和正文
                const thinkPart = text.substring(0, splitIndex)
                const resultPart = text.substring(splitIndex)
                
                if (thinkPart.trim()) {
                  this.thoughtContent += thinkPart
                }
                
                // 切换到正文模式
                this.isInThinkingMode = false
                this.resultContent += resultPart
              } else {
                // 未找到分割点，继续添加到思考内容
                this.thoughtContent += text
              }
            } else if (hasThinkEnd && this.isInThinkingMode) {
              // 检测到思考过程结束
              // 找到第一个匹配的思考结束标记
              let endIndex = -1
              for (const marker of thinkEndMarkers) {
                const idx = text.indexOf(marker)
                if (idx !== -1) {
                  const markerEnd = idx + marker.length
                  if (endIndex === -1 || markerEnd < endIndex) {
                    endIndex = markerEnd
                  }
                }
              }
              
              if (endIndex !== -1) {
                // 分离思考和正文
                const thinkPart = text.substring(0, endIndex)
                const resultPart = text.substring(endIndex)
                
                this.thoughtContent += thinkPart
                this.isInThinkingMode = false
                
                if (resultPart.trim()) {
                  this.resultContent += resultPart
                }
              } else {
                this.thoughtContent += text
                this.isInThinkingMode = false
              }
            } else {
              // 根据当前模式决定添加到哪个内容
              if (this.isInThinkingMode) {
                this.thoughtContent += text
              } else {
                this.resultContent += text
              }
            }
          }
          break
          
        case 'node_finished':
          // 更新节点状态
          const finishedIndex = this.workflowSteps.findIndex(n => n.nodeId === data.data.node_id)
          if (finishedIndex !== -1) {
            this.workflowSteps[finishedIndex].status = data.data.status
            if (data.data.outputs) {
              this.workflowSteps[finishedIndex].outputs = data.data.outputs
            }
          }
          break
          
        case 'workflow_finished':
          this.isLoading = false
          // 添加结束节点
          this.workflowSteps.push({
            nodeId: 'end',
            title: '结束',
            status: 'succeeded'
          })
          if (data.data && data.data.outputs) {
            console.log('工作流输出:', data.data.outputs)
          }
          break
          
        case 'error':
          this.isLoading = false
          this.$message.error(data.message || 'Workflow 执行错误')
          break
      }
    },
    
    /**
     * 停止 Workflow
     */
    async stopWorkflow() {
      if (!this.currentTaskId) {
        return
      }
      
      try {
        if (this.streamController) {
          this.streamController.abort()
        }
        await stopWorkflowTask(this.currentTaskId, this.appName)
        this.isLoading = false
        this.$message.success('已停止 Workflow 执行')
      } catch (error) {
        console.error('停止 Workflow 失败:', error)
        this.$message.error('停止 Workflow 失败')
      }
    },
    
    /**
     * 清除输入
     */
    clearInput() {
      this.userInput = ''
    },
    
    /**
     * 刷新页面
     */
    refreshPage() {
      this.clearInput()
      this.clearResult()
      this.workflowSteps = []
    },
    
    /**
     * 切换思考过程显示/隐藏
     */
    toggleThought() {
      this.thoughtCollapsed = !this.thoughtCollapsed
    },
    
    
    /**
     * 格式化消息（思考过程专用）
     */
    formatMessage(content) {
      if (!content) return ''

      // 清理思考过程内容，移除标签但保留内容
      let cleanContent = content
      
      // 移除标签，但保留标签内的内容
      cleanContent = cleanContent
        .replace(/<think>/gi, '')
        .replace(/<\/think>/gi, '')
        .replace(/<think>/gi, '')
        .replace(/<\/redacted_reasoning>/gi, '')
      
      // 如果包含 "◎ 思考过程"，移除这个标记但保留后续内容
      cleanContent = cleanContent.replace(/◎\s*思考过程[^\n]*\n?/gi, '')

      // 思考过程内容直接格式化
      return this.formatTextContent(cleanContent, 'think')
    },
    
    /**
     * 格式化结果内容（正文专用）
     */
    formatResultMessage(content) {
      if (!content) return ''

      // 清理所有思考过程相关的内容
      let cleanContent = content
      
      // 移除思考过程标签及其内容
      cleanContent = cleanContent
        .replace(/<think>[\s\S]*?<\/think>/gi, '')
        .replace(/<think>[\s\S]*?<\/think>/gi, '')
        .replace(/<think>[\s\S]*?<\/redacted_reasoning>/gi, '')
        .replace(/<think>[\s\S]*?<\/redacted_reasoning>/gi, '')
        .replace(/<think>[\s\S]*?<\/think>/gi, '')
      
      // 移除以 "◎ 思考过程" 开头的整个段落
      cleanContent = cleanContent.replace(/◎\s*思考过程[^\n]*\n[\s\S]*?(?=\n\n|$)/gi, '')
      
      // 移除思考过程关键词段落
      cleanContent = cleanContent.replace(/思考过程\([^)]+\)[\s\S]*?(?=\n\n|$)/gi, '')
      
      // 清理不完整的标签
      cleanContent = cleanContent
        .replace(/<think>\s*$/gi, '')
        .replace(/<\/think>\s*$/gi, '')
        .replace(/<think>\s*$/gi, '')
        .replace(/<\/redacted_reasoning>\s*$/gi, '')

      // 直接格式化正文内容
      return this.formatTextContent(cleanContent.trim(), 'main')
    },

    /**
     * 格式化文本内容（参考 MeetingMinutes.vue）
     */
    formatTextContent(text, type = 'main') {
      if (!text) return ''

      // 思考内容：移除重复段落
      if (type === 'think') {
        const paragraphs = text
          .split(/\n{2,}/)
          .map(p => p.trim())
          .filter(Boolean)
        const seen = new Set()
        const deduped = []
        for (const p of paragraphs) {
          const key = p.replace(/\s+/g, ' ')
          if (!seen.has(key)) {
            seen.add(key)
            deduped.push(p)
          }
        }
        text = deduped.join('\n\n')
      }

      // 移除可能残留的 think 标签
      let formatted = text.replace(/<\/?think>/gi, '').replace(/<\/?redacted_reasoning>/gi, '')

      // 保存 HTML 标签
      const htmlPlaceholders = []
      formatted = formatted.replace(/<img[^>]*>/g, (match) => {
        const index = htmlPlaceholders.length
        htmlPlaceholders.push(match)
        return `__HTML_PLACEHOLDER_${index}__`
      })
      formatted = formatted.replace(/<a[^>]*>.*?<\/a>/g, (match) => {
        const index = htmlPlaceholders.length
        htmlPlaceholders.push(match)
        return `__HTML_PLACEHOLDER_${index}__`
      })

      // 处理代码块
      const codeBlockPlaceholders = []
      formatted = formatted.replace(/```(\w+)?\n?([\s\S]*?)```/g, (match, lang, code) => {
        const index = codeBlockPlaceholders.length
        const escapedCode = code.trim()
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
        codeBlockPlaceholders.push(`<pre class="code-block"><code>${escapedCode}</code></pre>`)
        return `__CODE_BLOCK_${index}__`
      })

      // 处理行内代码
      const inlineCodePlaceholders = []
      formatted = formatted.replace(/`([^`]+)`/g, (match, code) => {
        const index = inlineCodePlaceholders.length
        const escapedCode = code
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
        inlineCodePlaceholders.push(`<code class="inline-code">${escapedCode}</code>`)
        return `__INLINE_CODE_${index}__`
      })

      // 转义普通文本中的 HTML 标签
      formatted = formatted
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')

      // 精简空行
      formatted = formatted
        .replace(/^\n+/, '')
        .replace(/\n+$/, '')
        .replace(/\n{2,}/g, '\n')

      // 处理 Markdown 语法
      formatted = formatted.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
      formatted = formatted.replace(/\n/g, '<br style="line-height: 1.6; margin: 0; padding: 0;">')

      // 恢复占位符
      codeBlockPlaceholders.forEach((code, index) => {
        formatted = formatted.replace(`__CODE_BLOCK_${index}__`, code)
      })
      inlineCodePlaceholders.forEach((code, index) => {
        formatted = formatted.replace(`__INLINE_CODE_${index}__`, code)
      })
      htmlPlaceholders.forEach((html, index) => {
        formatted = formatted.replace(`__HTML_PLACEHOLDER_${index}__`, html)
      })

      // 根据类型包装内容
      if (type === 'think') {
        // 生成唯一的 ID
        const thinkId = `think-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
        return `<div class="think-block">
          <div class="think-header" onclick="toggleThinkBlock('${thinkId}')">
            <i class="el-icon-view"></i>
            <span>思考过程</span>
            <i class="el-icon-arrow-down think-toggle-icon" id="icon-${thinkId}"></i>
          </div>
          <div class="think-content collapsed" id="content-${thinkId}">${formatted}</div>
        </div>`
      } else {
        return `<div class="main-content">${formatted}</div>`
      }
    },
    
    /**
     * 复制结果
     */
    copyResult() {
      if (!this.resultContent) {
        return
      }
      
      // 移除 HTML 标签，只复制纯文本
      let textContent = this.resultContent
        .replace(/<think>[\s\S]*?<\/think>/gi, '')
        .replace(/<[^>]+>/g, '')
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&')
        .replace(/<br\s*\/?>/gi, '\n')
        .trim()

      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(textContent)
          .then(() => {
            this.$message.success('已复制到剪贴板')
          })
          .catch(() => {
            this.fallbackCopy(textContent)
          })
      } else {
        this.fallbackCopy(textContent)
      }
    },

    fallbackCopy(text) {
      const textarea = document.createElement('textarea')
      textarea.value = text
      textarea.style.position = 'fixed'
      textarea.style.opacity = '0'
      document.body.appendChild(textarea)
      textarea.select()
      try {
        document.execCommand('copy')
        this.$message.success('已复制到剪贴板')
      } catch (err) {
        this.$message.error('复制失败，请手动复制')
      }
      document.body.removeChild(textarea)
    },
    
    /**
     * 切换工作流过程折叠/展开
     */
    toggleWorkflowSteps() {
      this.workflowStepsCollapsed = !this.workflowStepsCollapsed
    },
    
    /**
     * 清除结果
     */
    clearResult() {
      this.resultContent = ''
      this.thoughtContent = ''
      this.workflowSteps = []
      this.thoughtTime = 0
    }
  }
}
</script>

<style scoped>
.workflow-page {
  position: relative;
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #f5f7fa 0%, #e0e7ff 50%, #f0f4ff 100%);
  overflow: hidden;
}

.page-disabled-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
}

.mask-content {
  background: white;
  padding: 40px;
  border-radius: 12px;
  text-align: center;
  max-width: 500px;
}

.mask-icon {
  font-size: 48px;
  color: #f56c6c;
  margin-bottom: 20px;
}

.mask-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #303133;
}

.mask-desc {
  font-size: 16px;
  color: #606266;
  line-height: 1.6;
}

/* 机器人背景层（作为结果区域的背景） */
.result-section .robot-background-layer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  pointer-events: none;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.result-section .robot-background {
  width: 100%;
  height: 100%;
  max-width: none;
  max-height: none;
  min-width: auto;
  object-fit: contain;
  object-position: center;
  filter: drop-shadow(0 30px 60px rgba(59, 130, 246, 0.3)) brightness(1.2) contrast(1.15) saturate(1.1);
  animation: float 25s infinite ease-in-out;
  opacity: 0.6;
  z-index: 0;
  position: relative;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) translateX(0px) scale(1);
  }
  33% {
    transform: translateY(-15px) translateX(10px) scale(1.01);
  }
  66% {
    transform: translateY(10px) translateX(-5px) scale(0.99);
  }
}

/* 主布局：左右分栏 */
.main-layout {
  position: relative;
  z-index: 10;
  display: flex;
  width: 100%;
  height: 100vh;
  background: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(0.3px);
  -webkit-backdrop-filter: blur(0.3px);
}

/* 左侧面板 */
.left-panel {
  width: 33.33%;
  min-width: 400px;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.4);
  backdrop-filter: blur(2px);
  -webkit-backdrop-filter: blur(2px);
  border-right: 1px solid rgba(229, 231, 235, 0.5);
  padding: 20px;
  overflow-y: auto;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.03);
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e5e7eb;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.collapse-icon {
  font-size: 16px;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s;
  padding: 4px;
  border-radius: 4px;
}

.collapse-icon:hover {
  color: #3b82f6;
  background: rgba(59, 130, 246, 0.1);
}

.panel-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  font-family: var(--font-family-fangsong);
}

.refresh-icon {
  font-size: 18px;
  color: #6b7280;
  cursor: pointer;
  transition: color 0.2s;
}

.refresh-icon:hover {
  color: #3b82f6;
}

/* 输入区域 */
.input-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

.section-label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 8px;
  font-family: var(--font-family-fangsong);
}

.input-textarea {
  flex: 1;
  min-height: 300px;
  padding: 12px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.6;
  color: #1f2937;
  background: #ffffff;
  resize: vertical;
  font-family: var(--font-family-fangsong);
}

.input-textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.input-textarea:disabled {
  background: #f9fafb;
  cursor: not-allowed;
}

.input-textarea::placeholder {
  color: #9ca3af;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 12px;
}

.btn-clear,
.btn-execute {
  flex: 1;
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  font-family: var(--font-family-fangsong);
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.btn-clear {
  background: #f3f4f6;
  color: #374151;
}

.btn-clear:hover:not(:disabled) {
  background: #e5e7eb;
}

.btn-execute {
  background: #3b82f6;
  color: #ffffff;
}

.btn-execute:hover:not(:disabled) {
  background: #2563eb;
}

.btn-execute:disabled,
.btn-clear:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 右侧面板 */
.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.4);
  backdrop-filter: blur(2px);
  -webkit-backdrop-filter: blur(2px);
  padding: 20px;
  overflow-y: auto;
}

/* 工作流步骤 */
.workflow-steps {
  margin-bottom: 20px;
  padding: 15px;
  background: rgba(249, 250, 251, 0.6);
  border-radius: 8px;
  border: 1px solid rgba(229, 231, 235, 0.7);
  transition: all 0.3s ease;
  overflow: hidden;
  max-height: 1000px;
  opacity: 1;
}

.workflow-steps.collapsed {
  max-height: 0;
  padding: 0 15px;
  margin-bottom: 0;
  opacity: 0;
  border: none;
}

.step-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  margin-bottom: 8px;
  background: #ffffff;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
  transition: all 0.2s;
}

.step-item:last-child {
  margin-bottom: 0;
}

.step-item.running {
  border-color: #3b82f6;
  background: #eff6ff;
}

.step-item.completed {
  border-color: #10b981;
  background: #f0fdf4;
}

.step-item.failed {
  border-color: #ef4444;
  background: #fef2f2;
}

.step-icon {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.step-icon i {
  font-size: 18px;
}

.step-item.running .step-icon i {
  color: #3b82f6;
  animation: rotating 2s linear infinite;
}

.step-item.completed .step-icon i {
  color: #10b981;
}

.step-item.failed .step-icon i {
  color: #ef4444;
}

.step-content {
  flex: 1;
}

.step-title {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  font-family: var(--font-family-fangsong);
}

.step-status {
  font-size: 12px;
  color: #6b7280;
  margin-top: 4px;
  font-family: var(--font-family-fangsong);
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 结果区域 */
.result-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  background: rgba(255, 255, 255, 0.3);
  border: 1px solid rgba(229, 231, 235, 0.6);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
}

.result-header {
  position: relative;
  z-index: 10;
  padding: 16px 20px;
  background: rgba(249, 250, 251, 0.8);
  backdrop-filter: blur(4px);
  -webkit-backdrop-filter: blur(4px);
  border-bottom: 2px solid #3b82f6;
}

.result-title {
  font-size: 16px;
  font-weight: 600;
  color: #3b82f6;
  font-family: var(--font-family-fangsong);
  display: flex;
  align-items: center;
  gap: 8px;
}

.result-title::before {
  content: '';
  width: 4px;
  height: 16px;
  background: #3b82f6;
  border-radius: 2px;
}

.result-content-wrapper {
  position: relative;
  z-index: 10;
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  min-height: 200px;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(2px);
  -webkit-backdrop-filter: blur(2px);
}

/* 思考过程 */
.thought-section {
  position: relative;
  z-index: 10;
  margin-bottom: 20px;
  background: rgba(240, 249, 255, 0.85);
  backdrop-filter: blur(4px);
  -webkit-backdrop-filter: blur(4px);
  border: 2px solid #3b82f6;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.15);
}

.thought-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
  border-bottom: 2px solid #3b82f6;
  cursor: pointer;
  transition: background 0.2s;
}

.thought-header:hover {
  background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
}

.thought-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #3b82f6;
  font-family: var(--font-family-fangsong);
}

.thought-title i {
  color: #3b82f6;
}

.thought-content {
  padding: 16px;
  max-height: 500px;
  overflow-y: auto;
  transition: all 0.3s ease;
  font-family: var(--font-family-fangsong);
  font-size: var(--font-size-content-primary);
  line-height: var(--line-height-content);
  color: #3b82f6;
  font-weight: var(--font-weight-normal);
}

.thought-content.collapsed {
  max-height: 0;
  padding: 0 16px;
  overflow: hidden;
}

/* 最终结果 */
.final-result {
  position: relative;
  z-index: 10;
}

.result-text {
  font-size: var(--font-size-content-primary);
  line-height: var(--line-height-content);
  color: #1f2937;
  font-family: var(--font-family-fangsong);
  font-weight: var(--font-weight-normal);
  white-space: pre-wrap;
  word-wrap: break-word;
}

.result-actions {
  position: absolute;
  top: 0;
  right: 0;
  display: flex;
  gap: 8px;
}

.action-btn {
  width: 32px;
  height: 32px;
  padding: 0;
  background: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  color: #6b7280;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.action-btn:hover {
  background: #f3f4f6;
  border-color: #3b82f6;
  color: #3b82f6;
}

/* 加载指示器 */
.loading-indicator {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 20px;
  text-align: center;
  color: #6b7280;
}

.loading-indicator i {
  font-size: 20px;
  animation: rotating 2s linear infinite;
  color: #3b82f6;
}

.stop-btn {
  margin-left: auto;
  padding: 6px 12px;
  background: #ef4444;
  color: #ffffff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.stop-btn:hover {
  background: #dc2626;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #9ca3af;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state p {
  font-size: 14px;
}

/* 思考块样式（参考 MeetingMinutes.vue） */
.think-block {
  background: #eff6ff;
  border-left: 3px solid #3b82f6;
  border-radius: 6px;
  padding: 6px 12px;
  margin-bottom: 12px;
  font-family: var(--font-family-fangsong);
}

.think-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 6px;
  margin-bottom: 4px;
  font-size: var(--font-size-content-secondary);
  color: #3b82f6;
  font-weight: var(--font-weight-semibold);
  font-family: var(--font-family-fangsong);
  cursor: pointer;
  user-select: none;
  transition: all 0.2s ease;
  padding: 2px 6px;
  border-radius: 4px;
}

.think-header:hover {
  color: #2563eb;
  background: rgba(59, 130, 246, 0.1);
}

.think-header i:first-child {
  font-size: 16px;
  color: #3b82f6;
}

.think-toggle-icon {
  font-size: 14px;
  color: #3b82f6;
  transition: transform 0.2s ease;
}

.think-content {
  font-size: var(--font-size-content-primary);
  line-height: var(--line-height-content);
  color: #3b82f6;
  font-family: var(--font-family-fangsong);
  padding-left: 8px;
  transition: all 0.3s ease;
  overflow: hidden;
  font-weight: var(--font-weight-normal);
}

.think-content.collapsed {
  max-height: 0;
  margin-bottom: 0;
  padding-top: 0;
  opacity: 0;
}

/* 正文内容样式 */
.main-content {
  font-size: var(--font-size-content-primary);
  line-height: var(--line-height-content);
  color: #1f2937;
  font-family: var(--font-family-fangsong);
  font-weight: var(--font-weight-normal);
}

.main-content ::v-deep strong {
  font-weight: 600;
  color: #111827;
}

.main-content ::v-deep code {
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
}

.main-content ::v-deep .code-block {
  background: #f8fafc;
  color: #334155;
  padding: 16px;
  border-radius: 8px;
  margin: 12px 0;
  overflow-x: auto;
  border: 1px solid #e2e8f0;
}

.main-content ::v-deep .inline-code {
  background: rgba(59, 130, 246, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  color: #1e40af;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .left-panel {
    min-width: 350px;
  }
}

@media (max-width: 768px) {
  .main-layout {
    flex-direction: column;
  }

  .left-panel {
    width: 100%;
    min-width: auto;
    max-height: 50vh;
  }

  .right-panel {
    flex: 1;
    min-height: 50vh;
  }
}
</style>
